import Vue from 'vue'
import Router from 'vue-router'
import Axios from "axios";
import Layout from '@/components/user/Layout'
import Index from '@/components/Index'
import Profile from '@/components/user/Profile'
import NotFound from '@/components/NotFound'
import Destroy from '@/components/user/Destroy'
import ChangePassword from '@/components/user/ChangePassword'



Vue.use(Router)

let router = new Router({
  //使用HTML5的History API
  mode: "history",
  routes: [
    {
      path: "/login",
      name: "登录",
      // 异步加载组件，可以按需下载js文件
      component: resolver => require(["@/components/Login.vue"], resolver)
    },
    {
      path: '/',
      name: '首页',
      component: Index,
    },
    {
      path: '/user',
      name: '布局',
      component: Layout,
      children: [
        {
          path: 'profile',
          name: '个人信息',
          component: Profile
        },
        {
          path: 'changePassword',
          name: '修改密码',
          component: ChangePassword
        },
        {
          path: 'Destroy',
          name: '销户',
          component: Destroy
        },
        {
          path: '*',
          name: '未找到',
          component: NotFound
        }
      ]
    }
  ]
})

//增加全局路由的守卫（过滤器、拦截器）
router.beforeEach((to, from, next) => {

  // console.log(to);
  // console.log(from);


  //如果路由要继续执行，必须调用next（）
  next();
});

// 服务端返回的CORS相关的响应头，需要浏览器保存Cookie
// 对应后端的 configuration.setAllowCredentials(true);
Axios.defaults.withCredentials = true;

//如果是AJAX请求，需要使用AXIOS的拦截器来处理请求的拦截
Axios.interceptors.request.use(config => {
  //请求发生之前
  // console.log("发送请求");
  return config;
}, error => {
  //发送请求出现错误
  console.error(error);
  return Promise.reject(error);
});

Axios.interceptors.response.use(response => {
  //响应没有出现错误，200、302等
  // console.log("请求完成，状态码: " + response.status);
  return response;
}, error => {
  // console.error("错误信息");
  if(error.response.status ===403){
    //跳转到登录页面，需要把授权地址作为参数传递给登录页面
    router.push({name:"登录",params:{redirectUrl: error.request.responseURL}})
  }else{
    //响应出现问题，403、404、500
    console.error(error);
  }
  return Promise.reject(error);
});


export default router;